<?php
 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mtask extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
       // $this->load->library('email');
        
    }
    
    public function addTask()
    {
        //Get params
        $module_name = $this->getParamString("module_name");
        $content = $this->getParamString("content");
        $users = $this->getParamArray("users");
        $time_start = $this->getParamString("time_start");
        $time_end = $this->getParamString("time_end");
        $module_name = $this->getParamString("module_name");
        $projectId=$this->getParamString("id");
        $user_id=$this->session->userdata('admin_id');
        $time_start= date('y-m-d',strtotime(str_replace('/', '-', $time_start))); // d/m/y ->d-m-y thì strtotime mới nhận
        $time_end= date('y-m-d',strtotime(str_replace('/', '-', $time_end))); // d/m/y ->d-m-y thì strtotime mới nhận
        $arrayInsert = array(
        'module_name' => $module_name,
        'content' => $content,
        'time_start' => $time_start,
        'time_end' => $time_end,
        'user_id' => $user_id,   
        'project_id' => $projectId,
        'status'=>  0   ,              //0 mới tạo ra,1 đang nhận và xử lí,2 là hoàn thành
        'created'=> date("Y-m-d H:i:s")    
        );
        //Insert vào bảng module
        $this->db->insert('module', $arrayInsert);
        $insertId=$this->db->insert_id();
        //Insert vào bảng module_user
        foreach ($users as $value)
        {
           $array=array('user_id'=>$value,'module_id'=>$insertId,'project_id'=>$projectId);
           $this->db->insert('module_key', $array);
           $this->sendMailUser($value, $arrayInsert);
        }  
        
        
        return 200;
    }
    public function editTask($taskId,$oldUser)
    {
        //Get params
        $module_name = $this->getParamString("module_name");
        $content = $this->getParamString("content");
        $users = $this->getParamArray("users");
        $time_start = $this->getParamString("time_start");
        $time_end = $this->getParamString("time_end");
        $module_name = $this->getParamString("module_name");
        $projectId=$this->getParamString("id");
        $user_id=$this->session->userdata('admin_id');
		$status = $this->getParamInt('status');
        $time_start= date('Y-m-d',strtotime(str_replace('/', '-', $time_start))); // d/m/y ->d-m-y thì strtotime mới nhận
        $time_end=   date('Y-m-d',strtotime(str_replace('/', '-', $time_end))); // d/m/y ->d-m-y thì strtotime mới nhận
        $arrayInsert = array(
				'module_name' => $module_name,
				'content' => $content,
				'time_start' => $time_start,
				'time_end' => $time_end,
				'user_id' => $user_id,   
				'project_id' => $projectId,
				'status'=> $status
			);
        $userDelete=  array_diff($oldUser, $users);
        $userInsert= array_diff($users, $oldUser);
//        echo "<pre>";var_dump($oldUser,$users,$userInsert,$userDelete);die;
		//echo '<pre>';die(print_r($arrayInsert));
        //Insert vào bảng module
        $this->db->update('module', $arrayInsert,array("id"=>$taskId));
        
        //Delete module_user
        foreach ($userDelete as $value)
        {
            $run = $this->db->query("DELETE FROM module_key WHERE module_id = '$taskId' AND user_id = '$value' ");
        }
        
        //Insert mới module_user
        foreach ($userInsert as $value)
        {
           $array=array('user_id'=>$value,'module_id'=>$taskId,'project_id'=>$projectId);
           $this->db->insert('module_key', $array);
        }
        return 200;
    }

    public function getProject($projectId)
    {
        $query="SELECT * FROM project WHER id = '$projectId' ";
        $projects=$this->db->query("SELECT * FROM project WHERE id = '$projectId' ")->row();
        return $projects;
    }
    public function getUserProject($projectId)
    {
        $users=$this->db->query("SELECT user.* FROM user INNER JOIN project_key ON user.id = project_key.user_id WHERE project_key.project_id = '$projectId' ")->result_array();
        return $users;
    }
    public function getDetailTask($taskId)
    {
        $task=$this->db->query("SELECT * FROM module WHERE id = '$taskId' ")->row();
        return $task;
    }
    
    public function getUserSelected($taskId)
    {
        $task=$this->db->query("SELECT user.id FROM user INNER JOIN module_key ON user.id = module_key.user_id WHERE module_key.module_id = '$taskId' ")->result_object();
        $arr=array();
        foreach ($task as $value)
        {
            $arr[]=$value->id;
        }
        return $arr;
    }
    
    public function deleteTask($taskId)
    {
        $this->db->query("DELETE FROM module_key WHERE module_id = '$taskId'");
        $this->db->query("DELETE FROM module WHERE id = '$taskId'");
        return 200;
    }
    
    public function addRate($idUser,$module_id,$rate)
    {
        //
        $projectId=$this->db->query("SELECT project_id FROM module WHERE id = '$module_id'")->row()->project_id;
        
        if($projectId == null )return 201;  //không tồn tại project chứa module này
        
        $check=$this->db->query("SELECT * FROM project_key WHERE project_id = '$projectId' AND user_id='$idUser' ");
        if($check->num_rows()==0)return 201;  //user không thuộc project
        
        $check=$this->db->query("SELECT * FROM module_key WHERE user_id = '$idUser' AND module_id='$module_id' ");
         //Đây là insert
         if($check->num_rows() == 0)
         {
            return 201; //user không thuộc module
         }
        else {
            $this->db->update("module_key",array('user_id'=>$idUser,'module_id'=>$module_id,'rate'=>$rate),array('id'=>$check->row()->id));
            if($rate < 100)
            $this->db->update("project",array('status'=>1),array('id'=>$projectId));
            if($rate == 100)
             $this->db->update("project",array('status'=>2),array('id'=>$projectId));
            
            //Tính rate trung bình rồi lưu vào bảng avg_user_project
            $rate_avg=$this->db->query("SELECT SUM(rate)/Count(id) as avg_rate FROM module_key as m WHERE m.user_id='$idUser' AND m.project_id= '$projectId'")->row()->avg_rate;
            $date=date("Y-m-d");
            $arrayAvg=array(
                'rate_avg'=>$rate_avg,
                'project_id'=>$projectId,
                'date_save' => date('Y-m-d H:i:s'),
                'user_id'=>$idUser,  
            );
//            //Check xem trong ngày đã nhập lần nào chưa,nhập rồi thì update,chưa thì insert
            $checkAvg=$this->db->query(" SELECT * FROM avg_user_project as avg WHERE avg.user_id ='$idUser' AND avg.project_id = '$projectId' AND DATE_FORMAT(avg.date_save,'%Y-%m-%d') = '$date'");
            
            if($checkAvg->num_rows() == 0)$this->db->insert("avg_user_project",$arrayAvg);
            else 
            $this->db->update("avg_user_project",$arrayAvg,array('id'=>$checkAvg->row()->id));
            
            
            //Lấy 2 ngày cuối rồi tìm các ngày giữa 2 ngày cuối đó để insert

//            $twoLastDate=$this->db->query(" SELECT avg.rate_avg as rate,DATE_FORMAT(avg.date_save,'%d/%m/%Y') as date FROM avg_user_project as avg WHERE avg.user_id ='$idUser' AND avg.project_id = '$projectId' ORDER BY avg.date_save DESC LIMIT 2");
//            if($twoLastDate->num_rows() >= 2)
//            {
//                $twoLastDate=$twoLastDate->result_object();
//                $arrDate=array();
//                $arrRate=array();
//                $i=1;$rateInsert=0;
//                foreach($twoLastDate as $key => $value)
//                {
//                    if($i == 2)$rateInsert=$value->rate;   //đây chính là rate của cái thứ 2 từ dưới lên
//                    $arrDate[]=$value->date;
//                    $arrRate[]=$value->rate;
//                    $i++;
//                }
//                
//               
//                $date1 = $arrDate[1];
//                $date2 = $arrDate[0];
//
//                $datePeriod = $this->returnDates($date1, $date2);
//                $arrayBetween=array();
//
//                foreach ($datePeriod as $date)
//                {
//                     $arrayBetween[]=$date->format('Y-m-d');
//                }
//                $arrayDates=array_diff($arrayBetween, $arrDate);
//                
//                $i=1;
//                foreach ($arrayDates as $key => $value )
//                {
//                    if(($i != 1) && ($i != count($arrayDates)) )
//                    {
//                        $this->db->insert("avg_user_project",array(
//                        'rate_avg'=>0,
//                        'project_id'=>$projectId,
//                        'date_save' => $value,
//                        'user_id'=>$idUser,  
//                        ));
//                    }
//                    $i++;
//                }
//            }
                
            }
        return 200;
    }
    
    /**
     * Gửi email sau khi người dụng nhận 1 module mới.
     * 
     * @param int $user_id      id User
     * @param array $moDetail   Chi tiết module
     */
    public function sendMailUser($user_id,$moDetail)
    {
        $user = $this->db->query('SELECT * FROM user WHERE id = '.$user_id.' LIMIT 1')->row();
        $idProject=$moDetail['project_id'];
        $projectName=$this->db->query("SELECT project_name FROM project WHERE id ='$idProject' ")->row()->project_name;
        $config = array(
						'protocol' => 'smtp',
						'smtp_host' => $this->_smtp_host,
						'smtp_user' => $this->_smtp_user,
						'smtp_pass' => $this->_smtp_pass,
						'mailtype' => 'html'
                    );
        $this->load->library('email');
        $this->email->initialize($config);
        $body= "Module mới được nhận từ project ".$projectName."<br>";
        $body.= "Tên module: ".$moDetail['module_name']."<br>";
        $body.= "Nội dung: ".$moDetail['content']."<br>";
        $body.= "Thời gian thực hiện: ".date('d/m/Y',  strtotime($moDetail['time_start']))." - ".date('d/m/Y',  strtotime($moDetail['time_end']))."<br>";
        $body.= "Link Project : "."<a href='".site_url()."project-detail/".$idProject."'>".site_url()."project-detail/".$idProject."</a>"."<br>";
     
        $this->email->from($this->_smtp_user, 'Wicity');
        $this->email->to($user->email);  
        $this->email->subject($moDetail['module_name']);
        $this->email->message($body);    
        
        $a=$this->email->send();
    }
    
    public function testSend()
    {
        $config = array(
						'protocol' => 'smtp',
						'smtp_host' => $this->_smtp_host,
						'smtp_user' => $this->_smtp_user,
						'smtp_pass' => $this->_smtp_pass,
						'mailtype' => 'html'
                    );

        $this->load->library('email');
        $this->email->initialize($config);
        $this->email->from($this->_smtp_user, 'Wicity');
        $this->email->to("khoaitayran201291@gmail.com");  
        $this->email->subject('Email Test');
        $this->email->message("kakakaádfasdfsdafsdaasdfsd"); 
        $this->email->send(); 
    }
    
    public function testSend1(){
        $config = array(
                'protocol' => 'smtp',
                'smtp_host' => 'ssl://smtp.googlemail.com',
                'smtp_port' => '465',
                'smtp_user' => 'khoaitayran201291@gmail.com',
                'smtp_pass' => 'colen2012'//Nhớ đánh đúng user và pass nhé
        );
        $this->load->library('email');
        $this->email->initialize($config);
        
        $this->email->from('khoaitayran201291@gmail.com', 'Nguyen Thanh Tung');
        $this->email->to('khoaitayran201291@gmail.com');    
        $this->email->subject('Email Test');
        $this->email->message('Kiểm tra thư này đi có virus ak!!!');    
        
        $this->email->send();
        $this->email->print_debugger(array('headers'));

    }
    public function testSend2()
    {
        mail("someone@example.com","My subject",$msg);die;
    }
    
    public function stopM($idUser,$module_id,$reason)
    { 
        
            
        if($this->session->userdata("level") != 1)  //Nếu không phải admin
        {
            $check=$this->db->query("SELECT * FROM module_key WHERE module_id = '$module_id' AND user_id='$idUser'");
            if($check->num_rows()==0)return 201;  //user không thuộc module
        }
        
        $arr = array(
                'status'       =>  0,
            ); 
       
        $this->db->update('module', $arr,array('id'=>$module_id));
        $arrInsert= array(
                'user_id'=>$idUser,
                'module_id'=>$module_id,
                'reason'=>$reason,
                'created'=>date("Y-m-d H:i:s")
            
        );
        $this->db->insert('module_key_reason', $arrInsert);
        return 200;
            
          
    }
     public function startM($idUser,$module_id)
    { 
        if($this->session->userdata("level") != 1)  //Nếu không phải admin
        {
            $check=$this->db->query("SELECT * FROM module_key WHERE module_id = '$module_id' AND user_id='$idUser'");
            if($check->num_rows()==0)return 201;  //user không thuộc module
        }
        $arr = array(
                'status'       =>  1,
            ); 
        $this->db->update('module', $arr,array('id'=>$module_id));
        return 200;
    }
	
	public function arrayChangeUser($taskId)
    {
        $task = $this->db->query("SELECT user.id, user.fullname as name FROM user INNER JOIN module_key ON user.id = module_key.user_id WHERE module_key.module_id = '$taskId' ")->result_object();
        return $task;
    }
	
	public function changeuser($userchange,$userjoin,$module_id){
		$data = $this->db->query('SELECT * FROM module_key WHERE user_id = '.$userchange.' AND module_id = '.$module_id.' ');
		$id = $data->row()->id;
		$check = $this->db->query('SELECT * FROM module_key WHERE user_id = '.$userjoin.' AND module_id = '.$module_id.' ');
		if( $check->num_rows() == 0 ){ // chưa tồn tại => update thằng kia lên theo $id
			$this->db->update('module_key', array('user_id' => $userjoin),'id = '.$id.' ');
		}else{ // tồn tại rồi xóa userchange
			$this->db->delete('module_key', array('user_id' => $userchange, 'module_id' => $module_id) );
		}
		
		$comment = $this->db->query('SELECT id FROM module_key_comment WHERE user_id = '.$userchange.' AND module_id = '.$module_id.' ')->result_object();
		foreach( $comment AS $el=>$le ){
			$this->db->update('module_key_comment',array('user_id' => $userjoin),'id = '.$le->id.' ');
		}
		
		$reason = $this->db->query('SELECT id FROM module_key_reason WHERE user_id = '.$userchange.' AND module_id = '.$module_id.' ')->result_object();
		foreach( $reason AS $el=>$le ){
			$this->db->update('module_key_reason',array('user_id' => $userjoin),'id = '.$le->id.' ');
		}
		die('Thành công');
	}
	
}